/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-06-06 16:46:34
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-06-06 17:29:44
 * @FilePath: \vue3_upload_file\service\utils\chunkClearShedult.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const path = require('path');
const fse = require('fs-extra');
const schedule = require('node-schedule');

const UPLOAD_DIR = path.resolve(__dirname, '..', "target");

// 空目录删除
const remove = (file, stats) => {
  const now = new Date().getTime();

  const offset = now - stats.ctimeMs;

  if (offset > 2 * 60 * 1000) {
    fse.unlinkSync(file);
    console.log(file, "文件过期，删除");
  }
}

const scan = async (dir, callback) => {

  const files = await fse.readdirSync(dir);

  files.forEach(async (filename) => {

    const fileDir = path.resolve(dir, filename);

    const stats = await fse.statSync(fileDir);

    // 删除文件
    if (stats.isDirectory()) {

      scan(fileDir, remove);
      // 删除空文件夹
      if (fse.readdirSync(fileDir).length == 0) {
        fse.rmdirSync(fileDir);
      }
      return;
    }
    if(callback) {
      callback(fileDir, stats)
    }
  });
}

// scheduleJob参数
// * * * * * *
// ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │ │
// │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
// │ │ │ │ └───── month (1 - 12)
// │ │ │ └────────── day of month (1 - 31)
// │ │ └─────────────── hour (0 - 23)
// │ └──────────────────── minute (0 - 59)
// └───────────────────────── second (0 - 59, OPTIONAL)

const start = () => {
  // 每5秒
  schedule.scheduleJob("*/5 * * * * *", () => {
    console.log("定时清理chunks开始");
    scan(UPLOAD_DIR);
  });
}

module.exports = {
  start
}
